package net.aynt.blog.sys;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Timer;

import javax.servlet.ServletContext;

import net.aynt.blog.lucene.LuceneTasker;
import net.aynt.blog.pojo.SiteConfig;
import net.aynt.blog.pojo.User;
import net.aynt.core.db.DBManager;
import net.aynt.core.exception.Exceptions;
import net.aynt.core.mvc.SystemInit;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ketayao.search.IndexHolder;

public class SystemInitServlet implements SystemInit {
	protected final Logger logger = LoggerFactory.getLogger(getClass());
	
	public static IndexHolder indexHolder;
	
	@Override
	public void init(ServletContext context){
		try {
			// 初始化数据库数据
			initDatabase(context);
			// 启动lucene更新
			initLucene();
		} catch (Exception e) {
			logger.error("System initialize failure:" + Exceptions.getStackTraceAsString(e));
			System.exit(0);
		}
	}
	
	@SuppressWarnings("unchecked")
	private void initDatabase(ServletContext context) throws Exception{
		DBManager.initDataSource(null, "blog.properties");
		List<User> users = (List<User>)User.INSTANCE.list();
		if (users.size() < 1) {
			User user = new User();

			user.setUsername(Constants.blog_user_username);
			user.setEmail(Constants.blog_user_email);
			user.setNickname(Constants.blog_user_nickname);
			user.setPassword(Constants.blog_user_password);
			user.setRole(Byte.parseByte(Constants.blog_user_role));
			user.setSalt(Constants.blog_user_salt);
			user.setFrozen(Byte.parseByte(Constants.blog_user_frozen));
			user.save();
		}
		
		SiteConfig siteConfig = SiteConfig.INSTANCE.get(1);
		if (siteConfig == null) {
			siteConfig = new SiteConfig();
			siteConfig.setAbout(Constants.blog_siteConfig_about);
			siteConfig.setContactDescription(Constants.blog_siteConfig_contact);
			siteConfig.setIcp(Constants.blog_siteConfig_icp);
			siteConfig.setName(Constants.blog_siteConfig_name);
			siteConfig.setUrl(Constants.blog_siteConfig_url);
			
			siteConfig.save();
		} 
		
		

		context.setAttribute(Constants.SITE_CONFIG, siteConfig);
	}
	
	private void initLucene() throws IOException {
		long scheduleTime = 
				NumberUtils.toLong(Constants.blog_lucene_scheduleTime, 1000*60*5);
		
		LuceneTasker tasker = new LuceneTasker(Constants.blog_lucene_path ,scheduleTime);
		Timer timer = new Timer();
		// 从现在开始 1 秒钟之后，每隔 1 秒钟执行一次 job1
		timer.schedule(tasker, 0, tasker.getScheduleTime());
		
		File file = new File(Constants.blog_lucene_path);
		if (!file.exists()) {
			file.mkdir();
		}
		indexHolder = IndexHolder.init(file.getPath());
	}
}
